﻿using System;
using System.Web.UI;
using PropertyExpression.TypedDataBinding.Web;
using PropertyExpression.TypedDataBinding.Web.Example.Exapmle1.Model;
using PropertyExpression.TypedDataBinding.Web.WebControls;

namespace PropertyExpression.TypedDataBinding.Web.Example
{
    public partial class Example1Form : Page
    {
        protected readonly GroupBinder<A> aBinder = new GroupBinder<A>();
        private RepeaterBinder<B> bBinder;
        protected RepeaterBinder<C> cBinder;
        private readonly RepeaterBinder<Ider> iderBinder = new RepeaterBinder<Ider>();

        protected void Page_Init(object sender, EventArgs e)
        {
            aBinder.Add(TextBox1).Add(x => x.Text, x => x.Id);
            aBinder.Add(TextBox2);

            bBinder = aBinder.Repeater(Repeater1, x => x.Bs);

            cBinder = new RepeaterBinder<C> { DataSource = () => bBinder.Data.Cs };

            aBinder.DataFunc = () => DataFactory.Instance.GetById<A>(1);
        }

        protected void Literal1_OnTypedInit(Literal sender)
        {
            bBinder.Add(sender).Add(x => x.Text, x => x.Id);
        }

        protected void Repeater1_OnTypedInit(Repeater sender)
        {
            bBinder.Add(sender, cBinder);
        }

        protected void Literal2_OnTypedInit(Literal sender)
        {
            iderBinder.Add(sender).Add(x => x.Text, x => x.Id);
        }

        protected void TextBox4_OnTypedInit(TextBox sender)
        {
            cBinder.Add(sender).Add(x => x.Text, x => x.BId);
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            aBinder.FromModel();
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            aBinder.ToModel();
        }

        private class Ider
        {
            public int Id { get; set; }
        }

        protected void TextBox2_TextChanged(object sender, EventArgs e)
        {
            var ider = new Ider();
            iderBinder.ParentControl = ((Control)sender).Parent;
            iderBinder.DataFunc = () => ider;
            iderBinder.ToModel();

            cBinder.ParentControl = ((Control)sender).Parent;
            cBinder.DataFunc = () => DataFactory.Instance.GetById<C>(ider.Id);
            cBinder.ToModel();
        }
    }
}